# -*- coding: utf-8 -*-

from yzw.items import yzwSku
from zc_core.model.items import Catalog, ItemData
from zc_core.util.sku_id_parser import convert_id2code
import json
import math
from zc_core.util.http_util import *
from pyquery import PyQuery
from zc_core.util.encrypt_util import md5


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    jpy = PyQuery(response.text)
    for jpy1 in jpy('#cate-menu-list-item').items():
        cat1_name = jpy1('.cate-menu-list-item-wrapper span').text()
        cat1_id = md5(cat1_name + ":1")
        cat11 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat11)
        for jpy2 in jpy1('.cate-menu-list-panel-item').items():
            cat2_name = jpy2('.cate-menu-list-panel-main span').text()
            cat2_id = md5(cat2_name + ":2")
            cat22 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat22)
            for jpy3 in jpy2('.cate-menu-list-panel-vice a').items():
                cat3_id = re.search('\d+', jpy3.attr('href'))
                if cat3_id:
                    cat3_id = cat3_id.group()
                    cat3_name = jpy3.text()
                    cat33 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                    cats.append(cat33)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 维度：三级分页，解析sku列表页数
def parse_total_page(response):
    json_data = json.loads(response.text)

    return json_data['data']['totalPage']


# 维度：品牌，解析sku列表页数
def parse_brand_total_page(response):
    page_json = json.loads(response.text)
    total_page = page_json['result']['pageTotal']

    return total_page


# 解析阶梯价格页数
def parse_price_page(num, size=20):
    return math.ceil(num / size)


def parse_price_page_xx(response):
    return json.loads(response.text)['result']['totalCount']


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog1Name = meta.get('catalog1Name')
    catalog1Id = meta.get('catalog1Id')
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    catalog3Name = meta.get('catalog3Name')
    catalog3Id = meta.get('catalog3Id')
    josn_data = json.loads(response.text)
    skus = list()
    for i in josn_data['data']['items'][0]['itemList']:
        sku = yzwSku()
        sku['skuId'] = i['skuId']
        sku['batchNo'] = batch_no
        sku['brandModel'] = i['model']
        sku['brandName'] = i['brandName']
        sku['brandId'] = i['brandId']
        sku['unit'] = i['unitName']
        sold_count = int(i['salesNum'])
        if sold_count < 0:
            sold_count = 0
        sku['soldCount'] = sold_count
        sku['skuImg'] = i['imageUrl']
        sku['supplierId'] = i['supplierId']
        sku['catalog1Id'] = catalog1Id
        sku['catalog1Name'] = catalog1Name
        sku['catalog2Id'] = catalog2Id
        sku['catalog2Name'] = catalog2Name
        sku['catalog3Id'] = catalog3Id
        sku['catalog3Name'] = catalog3Name
        skus.append(sku)
    return skus


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    catalog1Name = meta.get('catalog1Name')
    catalog1Id = meta.get('catalog1Id')
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    catalog3Name = meta.get('catalog3Name')
    catalog3Id = meta.get('catalog3Id')
    sold_count = meta.get('soldCount')
    try:
        json_text = re.search('window.g_initialData =(.*?);</script>', response.text, re.S).group(1)
        text = json_text.replace('undefined', '""')
        text = re.sub('"skuDescription":.*?},', "", text, re.S)
        json_data = json.loads(text)
    except:
        json_text = re.search('window.g_initialData = (.*?);</script>', response.text, re.S).group(1)
        text = json_text.replace('undefined', '""')
        # text = re.sub('"skuDescription":.*?},', "", text, re.S)
        text = re.sub('(,"html":.*?)}', '', text, re.S)
        try:
            json_data = json.loads(text)
        except:
            try:
                json_data = json.loads(text + "}")
            except:
                re_search=re.search('("attachmentModels":null.*?)"overall',text)
                if re_search:
                    json_data = json.loads(text.replace(re_search.group(1),"").strip()[:-1].strip().replace('null]','"None"').replace('null','"None"'))
                else:
                    print()
    for i in json_data['/product/{}'.format(sku_id)]['skuList']:
        # for jpy1 in jpy('.sku-item').items():
        #     jpy1('.textoverflow-2')
        result = ItemData()
        # 批次编号
        result['batchNo'] = batch_no
        # 平台商品ID（用于业务系统）
        result['skuId'] = i['id']
        # 平台商品名称（标题） #TODO
        try:
            skuName = i['brandName'].strip() + " " + i['groupName'].strip()
        except:
            skuName = i['itemName']
        result['skuName'] = skuName
        result['catalog1Name'] = catalog1Name
        result['catalog1Id'] = catalog1Id
        result['catalog2Name'] = catalog2Name
        result['catalog2Id'] = catalog2Id
        result['catalog3Name'] = catalog3Name
        result['catalog3Id'] = catalog3Id

        # 供应商商品编码
        result['supplierSkuId'] = i['code']
        # 供应商商品编号（无后缀）
        result['supplierSkuCode'] = i['code']

        # # 供应商名字 需要登录获取供应商
        # result['supplierName'] = "自营"
        # 供应商ID
        result['supplierId'] = i['supplierId']
        # 产品型号
        result['unit'] = i['unitName']
        # 主图列表
        result['skuImg'] = i['attachmentModels'][0].get('content')
        # 品牌名称
        result['brandName'] = i['brandName']
        # 品牌id
        result['brandId'] = i['brandId']
        # 库存
        result['stock'] = i['salesQuantity']
        # 累计销售
        result['soldCount'] = sold_count
        # 销售价格
        salePrice = i['price']
        if not salePrice:
            continue
        if salePrice!='None':
            result['salePrice'] = float(i['price'])
            # 商品原价
            result['originPrice'] = float(i['price'])
        # 最小起订量
        result['minBuy'] = i['buyStart']
        # 型号
        result['brandModel'] = i['model']
        yield result


if __name__ == '__main__':
    pass
